package secondriver.spark.core;

import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;

import java.io.File;
import java.time.LocalTime;

public class SparkEmitter {

    private static SparkEmitter sparkEmitter;

    private SparkConfigure sparkConfigure = new SparkConfigure() {

        @Override
        public void init() {
            Spark.setIpAddress("localhost");
            Spark.setPort(9000);
            Spark.externalStaticFileLocation(System.getProperty("user.dir")
                    + File.separator + "/public");
            Spark.staticFileLocation(".");
        }
    };
    private SparkFilter sparkFilter = new SparkFilter() {

        @Override
        public void init() {

        }
    };
    private SparkException sparkException = new SparkException() {

        @Override
        public void init() {

        }
    };
    private SparkHandler sparkHandler = new SparkHandler() {

        Route welcome = new Route() {

            @Override
            public Object handle(Request request, Response response) {
                return "<h2>" + "欢迎使用Spark" + "</h2>" + "<br/>" + "<h6>"
                        + LocalTime.now().toString() + "</h6>";
            }
        };

        @Override
        public void init() {
            Spark.get("/", welcome);
            Spark.get("/index", welcome);
        }
    };

    private SparkEmitter() {
        super();
    }

    private SparkEmitter(SparkConfigure sparkConfigure,
                         SparkFilter sparkFilter, SparkException sparkException,
                         SparkHandler sparkHandler) {
        super();
        if (null != sparkConfigure) {
            this.sparkConfigure = sparkConfigure;
        }
        if (null != sparkFilter) {
            this.sparkFilter = sparkFilter;
        }
        if (null != sparkHandler) {
            this.sparkHandler = sparkHandler;
        }
        if (null != sparkException) {
            this.sparkException = sparkException;
        }
    }

    public synchronized static SparkEmitter createSparkEmitter() {
        if (null == sparkEmitter) {
            sparkEmitter = new SparkEmitter();
        }
        return sparkEmitter;
    }

    public synchronized static SparkEmitter createSparkEmitter(
            SparkConfigure sparkConfigure, SparkFilter sparkFilter,
            SparkException sparkException, SparkHandler sparkHanlder) {
        if (null == sparkEmitter) {
            sparkEmitter = new SparkEmitter(sparkConfigure, sparkFilter,
                    sparkException, sparkHanlder);
        }
        return sparkEmitter;
    }

    public synchronized void launch() {
        // Notice: this.sparkConfigure.init() Must call firstly.
        this.sparkConfigure.init();
        this.sparkFilter.init();
        this.sparkHandler.init();
        this.sparkException.init();
    }
}